package com.zusmart.core.condition.extend;

import java.util.Map;

import com.zusmart.base.util.StringUtils;
import com.zusmart.core.bean.BeanDefinition;
import com.zusmart.core.condition.Condition;
import com.zusmart.core.condition.ConditionContext;
import com.zusmart.core.config.ConfigData;
import com.zusmart.core.config.ConfigSourceManager;
import com.zusmart.core.plugin.PluginManager;

public class ConditionalOnHasPropertyRule implements Condition {

	@Override
	public boolean matches(ConditionContext conditionContext, Map<String, BeanDefinition> beanDefinitions, BeanDefinition targetBeanDefinition, PluginManager pluginManager, ConfigSourceManager configSourceManager) {
		ConditionalOnHasProperty hasProperty = (ConditionalOnHasProperty) conditionContext.getExtendAnnotation();
		String prefix = hasProperty.prefix();
		String value = hasProperty.value();
		if (StringUtils.isBlank(value)) {
			return true;
		}
		return this.doMatches(conditionContext, beanDefinitions, targetBeanDefinition, configSourceManager, pluginManager, prefix, value);
	}

	protected boolean doMatches(ConditionContext conditionContext, Map<String, BeanDefinition> beanDefinitions, BeanDefinition targetBeanDefinition, ConfigSourceManager configSourceManager, PluginManager pluginManager, String prefix, String value) {
		String newValue = value;
		if (StringUtils.isNotBlank(prefix)) {
			if (prefix.endsWith(".")) {
				newValue = prefix + newValue;
			} else {
				newValue = prefix.substring(0, prefix.length() - 1) + newValue;
			}
		}
		ConfigData<Object> configData = configSourceManager.getConfigData(Object.class, newValue);
		if (null == configData || configData.isNotFound()) {
			return false;
		}
		return true;
	}

}